package org.ptkparty.client.activity;

import java.util.Collections;
import java.util.List;

import org.ptkparty.client.ClientFactory;
import org.ptkparty.client.Context;
import org.ptkparty.client.model.UserProxy;
import org.ptkparty.client.view.stats.StatsView;
import org.ptkparty.shared.dto.GameDto;

import com.google.gwt.activity.shared.Activity;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.web.bindery.requestfactory.shared.Receiver;

public class StatsActivity implements Activity {

	private ClientFactory clientFactory;
	private StatsView view;

	private List<UserProxy> users;

	private List<GameDto> datas;

	public StatsActivity(ClientFactory clientFactory, String currentChampionship) {
		this.clientFactory = clientFactory;
		Context.get().setCurrentChampionship(currentChampionship);
	}

	@Override
	public void start(AcceptsOneWidget panel, EventBus eventBus) {
		view = clientFactory.getStatsView();
		view.setPresenter(this);
		panel.setWidget(view);

		clientFactory.getFactory().userRequest().getUsersByChampionship(Context.get().getCurrentChampionship()).fire(new Receiver<List<UserProxy>>() {

			@Override
			public void onSuccess(List<UserProxy> response) {
				users = response;
			}
		});

		clientFactory.getPtkService().getFinishedGames(Context.get().getCurrentChampionship(), new AsyncCallback<List<GameDto>>() {

			@Override
			public void onFailure(Throwable caught) {

			}

			@Override
			public void onSuccess(List<GameDto> result) {
				Collections.reverse(result);
				datas = result;
				view.buildScoreStatsForAll();
			}

		});
	}

	@Override
	public String mayStop() {
		return null;
	}

	@Override
	public void onCancel() {
	}

	@Override
	public void onStop() {
	}

	public List<GameDto> getDatas() {
		return datas;
	}

	public List<UserProxy> getUsers() {
		return users;
	}

}
